package com.lee.mysql.controller;

import com.lee.mysql.vo.Result;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class LoginController {


    // 登录页面
    @RequestMapping(value = "/")
    public String loginIndex() {
        return "login";
    }


    // 退出登录
    @RequestMapping(value = "/doLoginOut")
    @ResponseBody
    public Result doLoginOut() {
        return Result.ofSuccess("退出成功");
    }


    /** 用户登陆认证方法 */
    @PostMapping(value = "/doLogin")
    @ResponseBody
    public Result doLogin(Boolean isRememberMe, String username, String password) {
        if(StringUtils.isBlank(username) || StringUtils.isBlank(password)){
            return new Result(Result.FAIL,"用户名或密码不能为空",null);
        }

        if (isRememberMe == null){
            isRememberMe = false;
        }

        //获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //对用户进行封装
        UsernamePasswordToken token = new UsernamePasswordToken(username, password);
        //判断是否保存登陆信息,true，底层会以cookie形式将用户信息写在客户端
        if(isRememberMe)token.setRememberMe(true);
        //对用户信息进行认证，将token提交给secruityManager
        subject.login(token);
        return Result.ofSuccess("操作成功");
    }




}
